package com.hm.pan.controller;

import java.net.InetAddress;
import java.sql.Timestamp;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;
import com.hm.pan.model.User;
import com.hm.pan.annotation.CheckLogin;
import com.hm.pan.annotation.NoLogin;
import com.hm.pan.model.LoginHistory;
import com.hm.pan.model.ResultObj;
import com.hm.pan.service.UserService;
import com.hm.pan.util.StringUtil;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import redis.clients.jedis.Jedis;

@RestController
@CheckLogin
public class UserController {

	@Resource
	private UserService userService;

	// 获取昵称
	@PostMapping("uesrcenter")
	public Map<String, Object> uesrcenter(HttpServletResponse response, @RequestParam("userName") String userName) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		User user = (User) userService.usercenter(userName);
		Map<String, Object> map = new HashMap<>();
		if ((userName.equals(user.getUserName()))) {
			map.put("message", "success");
			return map;
		} else {
			return null;
		}
//		user.setUserName(userName);
//		map.put(userName, user);
//		return map;
	}

	// 上传修改的昵称
	@PostMapping("un")
	public Object upload(@RequestParam("user") String userName) {
		return userName;
	}

	// 上传头像
	@PostMapping("tx")
	public Object upload(@RequestParam("user") String userPhoto, @RequestParam("file") MultipartFile file,
			HttpServletRequest req) throws Exception {
		String realPath = req.getServletContext().getRealPath("./");
		String filename = file.getOriginalFilename();
		String contentType = file.getContentType();
		if (contentType.contains("image")) {
			FileOutputStream outputStream = new FileOutputStream(realPath + filename);
			outputStream.write(file.getBytes());
			outputStream.close();
			return userPhoto;
		} else {
			return "上传失败";
		}
	}

	@Resource
	private Jedis Jedis;

	// 注册
	@PostMapping("register")
	@NoLogin
	public Map<String, Object> register(HttpServletResponse response, User user,
			@RequestParam("userName") String userName,

			@RequestParam("userPassword") String userPassword, @RequestParam("userEmail") String userEmail,
			@RequestParam("verification") String verification) throws NullPointerException {
		Timestamp newTime = new Timestamp(System.currentTimeMillis());
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String, Object> map = new HashMap<>();
		try {
			User userExist = (User) userService.login(userName);
			userExist.getUserName(); // 让代码出现异常
			map.put("message", "register_exist"); // 判断该用户名是否存在
			return map;
		} catch (Exception e) {
			System.out.println("有异常");
			String verificationCode = Jedis.get(userEmail); // 获取redis上的验证码
			if (StringUtil.isEmpty(userService.findEmail(userEmail))) { // 判断邮箱是否被注册过
				if (verification.equals(verificationCode)) {
					user.setUserName(userName);
					user.setUserEmail(userEmail);
					user.setUserPassword(StringUtil.MD5(userPassword));
					user.setRegisterTime(newTime); // 添加注册时间
					userService.register(user); // 添加用户进数据库
					map.put("message", "register_success"); // 注册成功发送message到前端
					return map;
				} else {
					map.put("message", "register_fail"); // 注册失败发送message到前端
					return map;
				}
			} else {
				map.put("message", "register_email_exist"); // 邮箱号被注册返回message到前端
				return map;
			}
		}
	}

	// 登录
	@PostMapping("logins")
	@NoLogin
	public JSONObject logins(HttpServletResponse response, HttpServletRequest request, HttpSession session,
			@RequestParam("userName") String userName, @RequestParam("userPassword") String userPassword)
			throws Exception {
		JSONObject jsonObject = new JSONObject();
		LoginHistory loginHistory = new LoginHistory();
		Browser browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser();
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String, Object> map = new HashMap<>();
		try { // 空指针异常捕获
			User user = (User) userService.login(userName);
			String md5UserPassword = StringUtil.MD5(userPassword); // MD5加密
			if ((userName.equals(user.getUserName())) && (md5UserPassword.equals(user.getUserPassword()))) {
				InetAddress addr = InetAddress.getLocalHost();

				Timestamp newTime = new Timestamp(System.currentTimeMillis()); // 获取系统时间
				loginHistory.setLoginBrowser(browser); // 获取浏览器信息
				loginHistory.setLoginDevice(addr.getHostName().toString()); // 获取本机计算机名称
				loginHistory.setLoginIp(addr.getHostAddress().toString()); // 获取本机IP
				loginHistory.setLoginTime(newTime); // 记录登录时间
				loginHistory.setUserId(user.getUserId()); // 用户id
				userService.addLoginHistroy(loginHistory); // 记录登录历史
				map.put("message", "success"); // 登陆成功
				map.put("userName", user.getUserName()); // 将用户名储存在userName
				map.put("userId", user.getUserId()); // 将用户id储存在userId中
				map.put("userPhoto", user.getUserPhoto()); // 将用户头像储存在userPhoto中
				map.put("userEmail", user.getUserEmail()); // 将用户邮箱储存在userEmail中
				session.setAttribute("user", user); // 创建session
				System.out.println("SESSION-ID:" + session.getId());
				return jsonObject.fluentPutAll(map); // 将jsonObject响应到前端

			} else {
				map.put("message", "password"); // 密码错误
				return jsonObject.fluentPutAll(map);
			}
		} catch (NullPointerException e) { // 用户名为空
			System.out.println("出现空指针");
			map.put("message", "userName");
			return jsonObject.fluentPutAll(map);
		}
	}

	// 获取用户信息
	@RequestMapping("selectNamePhoto")
	public Object selectNamePhoto(HttpSession session) {
		User user = (User) session.getAttribute("user");

		if (user != null) {
			return new ResultObj(200, user);
		}

//		Long userId = user.getUserId(); // 获取所有用户ID
//		Integer userId = 45; //获取某一个用户
//		User user = userService.selectNamePhoto(userId);
		return new ResultObj(400, user);
	}

	// 通过用户id，修改用户昵称
	@RequestMapping("updateName")
	public Object updateName(HttpSession session, String userName) {
		User user = (User) session.getAttribute("user");
		Long userId = user.getUserId();
		Boolean updateName = userService.updateName(userId, userName);
		user.setUserName(userName);
		session.setAttribute("user", user);
		System.out.println(user.getUserName());
		if (updateName == true) {
			return new ResultObj(200, updateName);
		}
		return new ResultObj(400, updateName);
	}

	// 修改头像
	@PostMapping("updatePhoto")
	public Object upload(@RequestParam("file") MultipartFile file, HttpSession session) throws Exception {
		String filename = file.getOriginalFilename();
		String contentType = file.getContentType();
		String realPath = "html/head/";
		Object object = session.getAttribute("user");
		if (object == null) {
			return new ResultObj(400, "no login", null);
		}
		User user = (User) object;
		if (contentType.contains("image")) {
			FileOutputStream outputStream = new FileOutputStream(realPath + filename);
			outputStream.write(file.getBytes());
			outputStream.close();
			Boolean updatePhoto = userService.updatePhoto(user.getUserId(), "/head/" + filename);
			user.setUserPhoto("/head/" + filename);
			session.setAttribute("user", user);
			if (updatePhoto) {
				return new ResultObj(200, "/head/" + filename);
			} else {
				return new ResultObj(400, "fail", null);
			}
		} else {
			return new ResultObj(400, "is not image", null);
		}
	}

	// 判断忘记密码发送验证码判断
	@PostMapping("verificationCode")
	@NoLogin
	public Object code(@RequestParam("verificationCode") String verificationCode,
			@RequestParam("userEmail") String userEmail) {
		ResultObj resultObj = new ResultObj();
		String code = Jedis.get(userEmail);
		System.out.println(code);
		if (verificationCode.equals(code)) {
			resultObj.setMessage("success"); // 验证码正确
			resultObj.setStatusCode(200);
		} else {
			resultObj.setMessage("fails"); // 验证码错误
			resultObj.setStatusCode(500);
		}
		return resultObj;
	}

	// 忘记密码
	@PostMapping("forgetPassword")
	@NoLogin
	public Object forgetPassword(@RequestParam("newPassword") String newPassword,
			@RequestParam("userEmail") String userEmail) {
		ResultObj resultObj = new ResultObj();
		String password = StringUtil.MD5(newPassword);
		if (userService.forgetPassword(password, userEmail)) {
			resultObj.setMessage("success");
			resultObj.setStatusCode(200);
		} else {
			resultObj.setMessage("fails");
			resultObj.setStatusCode(500);
		}
		return resultObj;
	}

	// 修改密码
	@PostMapping("upPassword")
	public Object updatePassword(@RequestParam("oldPassword") String oldPassword,
			@RequestParam("newPassword") String newPassword, HttpSession session) {
		User user = (User) session.getAttribute("user"); // 获取session对象
		String userPassword = StringUtil.MD5(newPassword); // 新密码加密
		Long userId = user.getUserId();
		ResultObj resultObj = new ResultObj();
		if (user.getUserPassword().equals(StringUtil.MD5(oldPassword))) { // 判断密码是否正确
			userService.updatePassword(userId, userPassword);
			resultObj.setMessage("修改成功");
			return resultObj;
		}
		resultObj.setMessage("密码不一致");
		return resultObj;
	}

	// 登录判断
	@RequestMapping("checkLogin")
	@NoLogin
	public Object checkLogin(HttpSession session) {
		ResultObj resultObj = new ResultObj();

		if (session.getAttribute("user") == null) {
			resultObj.setStatusCode(401);
			resultObj.setMessage("Unauthorized");
			return resultObj;
		}

		resultObj.setStatusCode(200);
		resultObj.setMessage("OK");

		return resultObj;
	}

	// 退出登录
	@PostMapping("logout")
	public Object logout(HttpSession session) {
		ResultObj resultObj = new ResultObj();
		session.removeAttribute("user");
		resultObj.setMessage("success");
		return resultObj;
	}

}
